<template>
  <AppNavBar> 商品详情 </AppNavBar>
  <div class="detail-con" v-if="goods">
    <Image width="100vw" style="margin-top: 53px" :src="goods.cover_url" />
    <Card :price="goods.price" :desc="goods.description" :title="goods.title">
      <template #tags>
        <tag plain type="danger">推荐</tag>
        &nbsp;
        <tag plain type="danger">精选</tag>
      </template>
      <template #footer>
        <Button type="warning" @click="addToCart">加入购物车</Button>
        <Button type="danger">立即购买</Button>
      </template>
    </Card>
    <tabs v-model:active="activeTab">
      <tab title="概述"><div class="details" v-html="goods.details"></div></tab>
      <tab title="热评"></tab>
      <tab title="相关图书"></tab>
    </tabs>
  </div>
</template>

<script>
import { ref } from 'vue'
import { getGoodsDetails } from '@/api/goods'
import { addCart } from '@/api/shopcart'
import AppNavBar from '@/components/library/AppNavBar.vue'
import { useRoute } from 'vue-router'
import { Image, Card, Tag, Button, Tabs, Tab, Toast } from 'vant'
import { useStore } from 'vuex'
export default {
  name: 'Detail',
  components: { AppNavBar, Image, Card, Tag, Button, Tabs, Tab },
  setup () {
    const route = useRoute()
    const goods = ref(null)
    const store = useStore()
    const activeTab = ref(0)
    getGoodsDetails(route.query.id).then(res => {
      goods.value = res.data.goods
    })
    // 添加到购物车
    const addToCart = () => {
      if (goods.value.stock > 0) {
        addCart({ goods_id: goods.value.id }).then(res => {
          if (res.status === 201 || res.status === 204) {
            Toast.success('添加成功！')
            store.dispatch('updateCartCount')
          }
        })
      } else {
        Toast.fail('库存不足！')
      }
    }
    return {
      goods,
      activeTab,
      addToCart
    }
  }
}
</script>

<style scoped lang='less'>
.details {
  :deep(img) {
    width: 100vw !important;
    height: unset !important;
  }
}
</style>
